
const defaultopts = {
    matchTemplate: false,
    viewport: 1920,
    unit: 'vw',
    fixed: 2,
};

const template = /<template>([\s\S]+)<\/template>/gi
const ZPXRegExp = /\b(\d+(\.\d+)?)px\b/;


module.exports = function (opts) {
    return {
        name: 'vite-style-vw-vh-loader',
        enforce: 'pre',
        transform(code, id) {
            if (!id.endsWith('.vue') || id.indexOf('/node_modules/') > -1) {
                return
            }

            let config = Object.assign({}, defaultopts, opts);

            let pxGlobalRegExp = new RegExp(ZPXRegExp.source, 'g');

            let callback = ($0, $1) => {
                if (!$1) return
                let val = $1 / config.viewport * 100;
                val = parseFloat(val.toFixed(config.fixed));
                return val === 0 ? val : val + config.unit;
            }


            if (config.matchTemplate) {
                let _source = ''
                if (template.test(code)) {
                    _source = code.match(template)[0]
                }

                if (pxGlobalRegExp.test(_source)) {
                    let $_source = _source.replace(pxGlobalRegExp, callback);
                    return code.replace(template, $_source)
                }
                return code;
            } else if (pxGlobalRegExp.test(code)) {
                return code.replace(pxGlobalRegExp, callback);
            } else {
                return code;
            }
        },
    }
}